<template>
  <div>
    <a-modal
      id="poster"
      title="选择答案模块图"
      v-model="visible"
      ok-text="保存"
      cancel-text="取消"
      @ok="save"
      @cancel="cancel"
      width="1000px"
    >
      <!-- 所有模版展示 -->
      <img
        @click="selectTap(i)"
        v-for="(item,i) in tmplsdata"
        :src="item.bgurl ? item.bgurl : item.infos[0]"
        :key="i"
        alt
        style="width: 110px;height:150px;margin:0 20px 0 0"
      />
      <!-- 选择之后显示 -->
      <div class="result_box" v-if="flag">
        <p>2. 设置图片中的内容</p>
        <div class="for_add_result_box">
          <div v-for="(item,i) in resultTmpls" :key="i">
            <!-- 显示和编辑系统模版图 -->
            <template v-if="item.bgurl">
              <div
                style="display:flex;flex-direction:row;justify-content:space-between;width:500px"
              >
                <p>图片{{i+1}}</p>
                <p style="color: #409eff" @click="delResult(i)">删除</p>
              </div>
              <div
                class="result"
                style="position:relative;left:0;top:0px;   display:flex;flex-direction:row;justify-content:flex-start"
              >
                <div style="position:relative;zoom:.4; ">
                  <img :src="selectTmpl.bgurl" />
                  <div
                    v-for="(k,idx) in item.infos"
                    :key="idx"
                    :style="'position:absolute;text-align:center;word-wrap: break-word;white-space: normal;word-break: break-all;font-size:'+k['fontSize']+'px;width:'+k['width']+'px;height:'+k['height']+'px;top:'+k['position'][1]+'px;left:'+k['position'][0]+'px;'"
                  >
                    <div
                      :class="k.fontStyle==2?'fonthori':'fontvert'"
                      :style="'width:'+k['width']+'px;height:'+k['height']+'px;'"
                    >{{k['content']}}</div>
                  </div>
                </div>
                <div>
                  <a-form>
                    <a-form-item v-for="(k,idx) in item.infos" :key="idx">
                      <a-input
                        :maxLength="k.length"
                        :placeholder="'最多输入'+k.length+'个字'"
                        v-model="k.content"
                      ></a-input>
                    </a-form-item>
                  </a-form>
                </div>
              </div>
              <a-row v-if="resultTmpls.length>0">
                <a-button
                  @click="addResult"
                  class="add_result_but"
                  icon="plus"
                  style="margin-top:50px"
                >添加图片</a-button>
              </a-row>
            </template>
            <!-- 显示用户自带模版图 -->
            <template v-else>
              <div
                class="result"
                style="position:relative;left:0;top:0px;   display:flex;flex-direction:row;justify-content:flex-start"
              >
                <div style="position:relative;zoom:.4; ">
                  <img v-for="(k,idx) in item.infos" :key="idx" :src="item.infos[idx]" />
                </div>
              </div>
            </template>
          </div>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script>
import Util from "@/components/canvas/canvsFontType.js";
import { getTmpls, getPaperInfo } from "@/api/paper";

export default {
  props: ["visible1"],
  data() {
    return {
      //  显示预览框
      componentData: [],
      uid: localStorage.getItem("uid"),
      flag: false,
      tmplsdata: [],
      resultTmpls: [],
      selectTmpl: {},
      result: [],
      arr: [],
      visible: ""
    };
  },
  watch: {
    //监听此组件显示与隐藏(避免子组件改变父组件的值)
    visible1: {
      handler(value) {
        this.visible = value;
      },
      immediate: true
    }
  },
  methods: {
    //初始化（获取所有模版）
    chooseUpImg() {
      // 获取图片模版
      var _this = this;

      var data = { uid: _this.uid };
      getTmpls(data)
        .then(res => {
          // console.log(res.data, "getTmpls");
          _this.tmplsdata = res.data.templates;
        })
        .catch(err => console.log(err));

      if (this.$route.query.paperId) {
        let data = {
          uid: _this.uid,
          paperId: this.$route.query.paperId
        };
        getPaperInfo(data)
          .then(res => {
            // console.log(res.data, "getPaperInfo");
            if (res.data["data"]) {
              var info = res.data["data"];
              _this.result = info.resultImgs;
              for (let i = 1; i <= _this.result.length; i++) {
                let data = {
                  positionNum: i,
                  id: "card" + i,
                  name: "1",
                  imgUrl: _this.result[i - 1]
                };
                _this.componentData.push(data);
              }
            }
          })
          .catch(err => console.log(err));
      }
    },
    //保存（但不上传oss）
    save() {
      var _this = this;
      if (Object.keys(this.selectTmpl).length == 0) {
        this.$notification["error"]({
          title: "错误",
          message: "还没设置选择图片"
        });
        return;
      }
      // console.log(_this.resultTmpls);
      if (
        _this.resultTmpls[0]["bgurl"] &&
        _this.resultTmpls[0]["bgurl"] != ""
      ) {
        _this.arr = [];
        _this.result = [];
        for (var idx = 0; idx < _this.resultTmpls.length; idx++) {
          var _reresultTmpls;
          _reresultTmpls = _this.resultTmpls[idx];
          _this.drawimg(_this.resultTmpls[idx], idx, function(dataURL) {
            _this.result.push(dataURL);
            for (let i = 1; i <= _this.result.length; i++) {
              var j = i;
              let data = {
                positionNum: j,
                id: "card" + j,
                name: "1",
                imgUrl: _this.result[i - 1],
                tmplId: _reresultTmpls["tmplId"]
              };
              // console.log(data);
              _this.arr[i - 1] = data;
              // console.log(_this.result.length);
              // console.log(_this.arr.length);
              if (_this.arr.length == _this.result.length) {
                _this.$emit("UpChooseDate", false, _this.arr);
              }
            }
          });
        }

        // console.log(_this.arr);
      } else {
        _this.arr = [];
        _this.result = [];
        _this.resultTmpls[0]["infos"].forEach((i, index) => {
          // console.log(index);
          _this.result.push(i);
          let data = {
            positionNum: index,
            id: "card" + index,
            name: "1",
            imgUrl: i,
            tmplId: _this.resultTmpls[0]["tmplId"]
          };
          _this.arr.push(data);
          // console.log(_this.result.length);
          // console.log(_this.arr.length);
        });
        _this.$emit("UpChooseDate", false, _this.arr);
      }
    },
    //取消（让父组件响应）
    cancel() {
      this.$emit("UpChooseDate");
    },
    // 选择图片模版
    selectTap(index) {
      this.index = index;
      this.selectTmpl = JSON.parse(JSON.stringify(this.tmplsdata[index]));
      this.resultTmpls = [this.selectTmpl];
      this.flag = true;

      // console.log(this.selectTmpl);
      // console.log(this.resultTmpls);
    },
    //删除
    delResult(index) {
      this.resultTmpls.splice(index, 1);
    },
    //添加
    addResult() {
      var obj = JSON.stringify(this.tmplsdata[this.index]);
      this.resultTmpls.push(JSON.parse(obj));
      // console.log(this.resultTmpls);
    },
    //canvas
    drawimg(tmpl, i, fun) {
      // var _this = this;
      // console.log(tmpl);
      let canvas = document.createElement("canvas");
      let ctx = canvas.getContext("2d");

      let img = new Image();
      img.setAttribute("crossOrigin", "anonymous");

      img.src = tmpl.bgurl + "?timeStamp=" + Date.parse(new Date()) + "_" + i;
      i++;
      // console.log(img);
      img.onload = function() {
        // console.log(img.width, img.height);
        canvas.width = img.width;
        canvas.height = img.height;
        ctx.drawImage(img, 0, 0, img.width, img.height);

        for (let item of tmpl.infos) {
          ctx.textAlign = "center";
          ctx.textBaseline = "middle";

          ctx.font = "bolder " + item.fontSize + "px Times New Roman";
          if (item.fontStyle == 1) {
            ctx.fillStyle = "black";

            if (item.color) {
              ctx.fillStyle = item.color;
            }
            Util.drawText(
              ctx,
              item["content"],
              item["position"][0],
              item["position"][1],
              item.width,
              item.height,
              false,
              true
            );
          } else {
            ctx.fillStyle = "white";
            if (item.color) {
              ctx.fillStyle = item.color;
            }

            Util.drawText(
              ctx,
              item["content"],
              item["position"][0] + item.width * 0.03,
              item["position"][1],
              item.width * 0.94,
              item.height,
              false,
              false
            );
          }
        }

        let dataURL = canvas.toDataURL("image/jpeg");
        fun(dataURL);
      };
    }
  },
  mounted() {
    this.chooseUpImg();
  }
};
</script>
<style lang="less" scoped>
.fonthori {
  writing-mode: horizontal-tb;
  display: table-cell;
  vertical-align: middle;
}
.fontvert {
  writing-mode: vertical-rl;
}
</style>